package com.chen.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chen.seckill.exception.GlobalException;
import com.chen.seckill.pojo.*;
import com.chen.seckill.mapper.OrderMapper;
import com.chen.seckill.resultvo.RespBeanEnum;
import com.chen.seckill.service.IGoodsService;
import com.chen.seckill.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.seckill.service.ISeckillGoodsService;
import com.chen.seckill.service.ISeckillOrderService;
import com.chen.seckill.utils.MD5Util;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenyuan
 * @since 2021-07-21
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private ISeckillGoodsService seckillGoodsService;
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ISeckillOrderService seckillOrderService;

    @Resource
    private IGoodsService goodsService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 秒杀功能具体实现
     * 在数据库表中，生成订单。
     *
     * @param user
     * @param goodsVO
     * @return
     */
    @Transactional
    @Override
    public Order seckill(User user, GoodsVO goodsVO) {
        //秒杀商品表 库存减一
        SeckillGoods goods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsVO.getId()));
        goods.setStockCount(goods.getStockCount()-1);
        /**
         * 一定要使用使用sql语句（不要使用mybatisplus的 update API）（可以使用setSql拼接SQL语句）
         * 并且添加秒杀条件  (and stock_count>0)
         * 来解决商品超卖问题
         */
        boolean result=seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().setSql("stock_count = stock_count-1").eq("goods_id",goods.getId()).gt("stock_count",0));
        //boolean result=seckillGoodsService.update(goods,new UpdateWrapper<SeckillGoods>().eq("goods_id",goods.getId()).gt("stock_count",0));
        if (goods.getStockCount()<1)
        {
            redisTemplate.opsForValue().set("isStockEmpty:"+goodsVO.getId(),"商品抢购结束");
            //System.out.println(result);
            return null;
        }
        //seckillGoodsService.updateById(goods);
        Order order=new Order();
        //生成订单
        order.setUserId(user.getId());
        order.setGoodsId(goodsVO.getId());
        order.setDeliverAddrId(0L);
        order.setGoodsName(goodsVO.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goodsVO.getId());
        seckillOrderService.save(seckillOrder);
        /**
         * 将秒杀订单保存在redis缓存中，
         * 避免一个用户抢购多个商品
         */
        redisTemplate.opsForValue().set("order:"+user.getId()+":"+goods.getId(),seckillOrder);
        return order;
    }

    /**
     * 订单详情返回对象
     * @param orderId
     * @return
     */
    @Override
    public OrderDetailVo detail(Long orderId) {
        if (orderId==null){
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        Order order = orderMapper.selectById(orderId);
        GoodsVO goodsVO = goodsService.findGoodsVOByGoodsId(order.getGoodsId());
        OrderDetailVo orderDetailVo=new OrderDetailVo();
        orderDetailVo.setOrder(order);
        orderDetailVo.setGoodsVO(goodsVO);
        return orderDetailVo;
    }

    /**
     * 获取秒杀接口地址（主要是为了实现接口地址隐藏）
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public String createPath(User user, Long goodsId) {
        String uuid=UUID.randomUUID().toString()+"123456";
        String md5 = MD5Util.md5(uuid);
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        stringObjectValueOperations.set("seckillPath:"+user.getId()+":"+goodsId,md5,60, TimeUnit.SECONDS);
        return md5;
    }

    /**
     * 校验秒杀地址
     * @param user
     * @param goodsId
     * @param path
     * @return
     */
    @Override
    public Boolean checkPath(User user, Long goodsId, String path) {
        if (user==null||goodsId<0|| StringUtils.isEmpty(path)){
            return false;
        }
        String redisPath = (String)redisTemplate.opsForValue().get("seckillPath:" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }

    /**
     * 校验验证码
     * @param user
     * @param goodsId
     * @param captcha
     * @return
     */
    @Override
    public Boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (StringUtils.isEmpty(captcha)||user==null||goodsId<0){
            return false;
        }
        String RedisCaptcha= (String)redisTemplate.opsForValue().get("captcha:"+user.getId()+":"+goodsId);
        return captcha.equals(RedisCaptcha);
    }
}
